﻿#include "tcpserver.h"

TCPServer::TCPServer(QWidget *parent) :
    QWidget(parent)
{

}


int TCPServer::Initialize(int Port)
{
    //1、初始化网络套接字库
    WSADATA         wsd;            //WSADATA变量
    if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0)
    {
        return -1;

    }
    n = 0;

    //2、创建套接字
    ServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    if (INVALID_SOCKET == ServerSocket)
    {
        return -2;
    }

    //3、处理地址----》网络套接字顺序
    ServerAddr.sin_family = AF_INET;
    ServerAddr.sin_port = htons(Port);
    ServerAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);

    //4绑定端口和ip
    bind(ServerSocket, (sockaddr*)&ServerAddr, sizeof(ServerAddr));
    listen(ServerSocket, 5);

    //设置异步套接字
     WSAAsyncSelect(ServerSocket,(HWND)this->winId(), WM_SOCKET, FD_ACCEPT | FD_READ);

    return 0;
}

 bool TCPServer::nativeEvent(const QByteArray &eventType, void *message, long *result)
 {
     Sleep(20);
     MSG* msg = (MSG*)message;
     char cs[100] = "";
     char *p;
     int lengther;
     std::string str;

     if(msg->message == WM_SOCKET)
     {
         if(WSAGETSELECTERROR(msg->lParam))
         {
             qDebug() << "发生错误";
         }
         else
         {
             switch (WSAGETSELECTEVENT(msg->lParam))
             {
             case FD_ACCEPT:
             {
                 lengther = sizeof(ClientAddr);
                 //接收客户端请求
                 ClientSocket = accept(ServerSocket, (sockaddr*)&ClientAddr, &lengther);
                 qDebug() << QString("[%1:%2] 连接服务器").arg(inet_ntoa(ClientAddr.sin_addr)).arg(ClientAddr.sin_port);
             }
                 break;

             case FD_READ:
             {
                 recv(ClientSocket, cs, 100, 0);
                 p = cs;
                 ReceivedPush(std::string(p));
                 qDebug() << cs;

             }
                 break;

             }

         }

     }

     //其他交给qt处理
     return QWidget::nativeEvent(eventType, message, result);
 }


int TCPServer::Send(std::string message)
{
    std::string str = "";
    if (message == "")
    {
        return 0;
    }
    else
    {
        //客户端套接字
        if (send(ClientSocket, message.c_str(), message.length(), 0) != SOCKET_ERROR)
        {
            return 0;
        }
        else
        {
            return -1;
        }
    }
}

void TCPServer::ReceivedClear()
{
    m_mutex.lock();
    m_Received.clear();
    m_mutex.unlock();
}

void TCPServer::ReceivedPush(std::string str)
{
    m_mutex.lock();
    m_Received.push_back(str);
    m_mutex.unlock();
}

std::string TCPServer::ReceivedPop()
{
    std::string str = "";
    m_mutex.lock();
    if(m_Received.size()  == 0)
    {
        return str;
    }
    str = m_Received.front();
    std::vector<std::string>::iterator k = m_Received.begin();
    m_Received.erase(k);
    m_mutex.unlock();
    return str;
}

int TCPServer::ReceivedSize()
{
    m_mutex.lock();
    auto size =  m_Received.size();
    m_mutex.unlock();
    return  (int)size;
}
